package com.itheima.health.webcontroller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.constants.MessageConstant;
import com.itheima.health.constants.RedisMessageConstant;
import com.itheima.health.entity.Result;
import com.itheima.health.service.LoginMobileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 用户手机登录控制层
 */
@RestController
@RequestMapping("/login")
public class LoginMobileController {

    @Reference
    private LoginMobileService loginMobileService;
    @Autowired
    private JedisPool jedisPool;

    /**
     * 用户登录验证
     * @param map
     * @return
     */
    @RequestMapping("/check")
    public Result findById(HttpServletResponse response, @RequestBody Map map) {
        try {
            Result result = null;
            // 获取电话
            String telephone = (String) map.get("telephone");
            String validateCode = (String) map.get("validateCode");
            // 获取redis
            Jedis jedis = jedisPool.getResource();
            // 通过手机号获取redis中的验证码
            String RedisCode = jedis.get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
            // 判断是否一致,或验证码是否已过期
            if (RedisCode == null || !RedisCode.equals(validateCode)) {
                // 抛出验证码错误异常
                result = new Result(false,MessageConstant.VALIDATECODE_ERROR);
                return result;
            }

            // 准备登录
            result = loginMobileService.login(map);
            // 创建cookie
            Cookie cookie = new Cookie("login_user_telephone", telephone);
            // 有效期一个月
            cookie.setMaxAge(30*24*60*60);
            // 全页面可用
            cookie.setPath("/");
            // 添加cookie
            response.addCookie(cookie);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.ORDER_FAIL);
        }

    }

}
